package oj.oj_94;

/**
 * 二叉树的中序遍历
 * https://leetcode.cn/problems/binary-tree-inorder-traversal/
 */

import oj.oj_144.TreeNode;
import java.util.*;
public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ans = new ArrayList<>();  // 这样只会有一个对象存在
        inorderInternal(root, ans);
        return ans;
    }

    private void inorderInternal(TreeNode root, List<Integer> ans) {
        if (root == null) {
            return;
        }

        inorderInternal(root.left, ans);
        ans.add(root.val);
        inorderInternal(root.right, ans);
    }

    public List<Integer> inorderTraversal1(TreeNode root) {
        List<Integer> ans = new ArrayList<>();  // 这个方法被调用多少次，ans 对象就要创建多少个
        if (root == null) {
            return ans;
        }

        ans.addAll(inorderTraversal1(root.left));
        ans.add(root.val);
        ans.addAll(inorderTraversal1(root.right));

        return ans;
    }

    public static void main(String[] args) {
        TreeNode n1 = new TreeNode(1);  // A
        TreeNode n2 = new TreeNode(2);  // B
        TreeNode n3 = new TreeNode(3);  // C
        TreeNode n4 = new TreeNode(4);  // D
        TreeNode n5 = new TreeNode(5);  // E
        TreeNode n6 = new TreeNode(6);  // F
        TreeNode n7 = new TreeNode(7);  // G
        TreeNode n8 = new TreeNode(8);  // H
        TreeNode n9 = new TreeNode(9);  // I
        TreeNode n10 = new TreeNode(10);    // J
        TreeNode n11 = new TreeNode(11);    // K

        n1.left = n2;   n1.right = n3;
        n2.left = n4;   n2.right = n5;
        n3.left = null; n3.right = n6;
        n4.left = null; n4.right = null;
        n5.left = n7;   n5.right = n8;
        n6.left = n9;   n6.right = null;
        n9.left = n10;  n9.right = n11;

        Solution solution = new Solution();
        List<Integer> list = solution.inorderTraversal(n1);
        System.out.println(list);
    }
}
